package tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-11-23
 * Time：23:45
 */
public class EchoClient {
    Socket socket = null;
    public EchoClient(String serverIp, int port) throws IOException {
        //建立连接，得知道服务端的ip和端口号
        socket = new Socket(serverIp, port);
    }

    public void start() {
        System.out.println("连接服务器成功");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scanner = new Scanner(System.in);
            while (true) {
                //1.接收用户输入
                System.out.print(">  ");
                String request = scanner.next();
                //2.发送到服务器
                printWriter.println(request);
                printWriter.flush();
                //3.接收服务器响应的数据
                String response = scannerNet.next();
                System.out.printf("request : %s, response : %s\n", request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        EchoClient echoClient = new EchoClient("127.0.0.1", 8000);
        echoClient.start();
    }
}
